﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;
using System.Diagnostics.CodeAnalysis;
using TrackSystem.Entities.Dtos.Channel;
using TrackSystem.Entities.Dtos.Sensor;
using TrackSystem.Entities.Extensions;
using TrackSystem.UI.Server.HttpRepository.Channel;
using TrackSystem.UI.Server.HttpRepository.Sensor;

namespace TrackSystem.UI.Server.Pages.Configuration
{
    public partial class ChannelTable
    {
        [Inject]
        [NotNull]
        private IStringLocalizer<ChannelDto>? Localizer { get; set; }

        [NotNull]
        private Table<ChannelDto>? TableColumnVisible { get; set; }

        [NotNull]
        private Modal? BackdropModal { get; set; }
        /// <summary>
        /// 获得/设置 分页配置数据源
        /// </summary>
        private static IEnumerable<int> PageItemsSource => new int[] { 10, 20, 40 };

        private readonly IEnumerable<SelectedItem> _lstPortCategory = new List<SelectedItem>
        {
            new SelectedItem() { Text = "TCP", Value = "0" },
            new SelectedItem() { Text = "UDP", Value = "1" },
            new SelectedItem() { Text = "串口", Value = "2" },
        };

        private IEnumerable<SelectedItem> _lstProtocol = new List<SelectedItem>();

        private bool _isTcp = true;

        private Task OnCategoryChanged(SelectedItem item)
        {
            // 处理分类变化逻辑
            _isTcp = !_isTcp;
            StateHasChanged();
            return Task.CompletedTask;
        }

        [Inject]
        public IChannelHttpRepository? Repo { get; set; }

        [Inject]
        [NotNull]
        private ToastService? ToastService { get; set; }

        protected override async Task OnInitializedAsync()
        {
            if (Repo == null)
            {
                throw new InvalidOperationException("Repository is not initialized.");
            }

            var protocols = Enum.GetValues(typeof(ProtocolEnum));
            foreach ( var protocol in protocols) {
                _lstProtocol = _lstProtocol.Append(new SelectedItem()
                {
                    Text = protocol.ToString() ?? string.Empty,
                    Value = ((int)protocol).ToString()
                });
            }

            // 初始化数据
            await base.OnInitializedAsync();
        }

        private async Task<QueryData<ChannelWithSensorsDto>> OnQueryAsync(QueryPageOptions options)
        {
            if (Repo == null)
            {
                await ToastService.Error("通道列表", "数据库未初始化");
                return new QueryData<ChannelWithSensorsDto>();
            }

            var items = await Repo.GetAllWithSensors();

            items = items.Where(options.ToFilterFunc<ChannelWithSensorsDto>());

            // 排序
            var isSorted = false;
            if (!string.IsNullOrEmpty(options.SortName))
            {
                items = items.Sort(options.SortName, options.SortOrder);
                isSorted = true;
            }

            var total = items.Count();
            var result = new QueryData<ChannelWithSensorsDto>()
            {
                Items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList(),
                TotalCount = total,
                IsFiltered = true,
                IsSorted = isSorted,
                IsSearch = true
            };

            return result;
        }


        private async Task<bool> OnSaveAsync(ChannelWithSensorsDto chn, ItemChangedType changedType)
        {
            if (Repo == null)
            {
                await ToastService.Error("通道列表", "数据库未初始化");
                return false;
            }

            var ret = false;
            if (changedType == ItemChangedType.Add)
            {
                var result = await Repo.InsertAsync(chn);
                if (!result.Success)
                {
                    await ToastService.Error("通道列表", result.Message);
                }
                return result.Success;
            }
            else if (changedType == ItemChangedType.Update)
            {
                var result = await Repo.UpdateAsync(chn);
                if (!result.Success)
                {
                    await ToastService.Error("通道列表", result.Message);
                }
                return result.Success;
            }
            return await Task.FromResult(ret);
        }

        private async Task<bool> OnDeleteAsync(IEnumerable<ChannelWithSensorsDto> chns)
        {
            if (Repo == null)
            {
                await ToastService.Error("通道列表", "数据库未初始化");
                return false;
            }

            bool ret = true;
            foreach(var item in chns)
            {
                var result = await Repo.DeleteAsync(item.Id);
                if (result.Success)
                {
                    continue;
                }

                await ToastService.Error("通道列表", result.Message);
                ret = false;
            }
            return ret;
        }

        [Inject]
        [NotNull]
        public DialogService? DialogService { get; set; }

        [Inject]
        [NotNull]
        public required ISensorHttpRepository sensorRepo { get; set; }


        private async Task SkipToSensor(int id)
        {
            var result = await sensorRepo.GetSingleSensor(id);
            if (!result.Success)
            {
                return;
            }
            var Sensor = result.Data ??= new SensorWithChannelDto();
            var option = new EditDialogOption<SensorWithChannelDto>()
            {
                Title = "传感器信息",
                Model = Sensor,
                RowType = RowType.Inline,
                ShowLoading = true,
                ItemsPerRow = 2,
                ItemChangedType = ItemChangedType.Update,
                OnEditAsync = async context =>
                {
                    var ret = await sensorRepo.UpdateAsync((SensorWithChannelDto)context.Model);
                    if (!result.Success)
                    {
                        await ToastService.Error($"传感器{Sensor.Name}", result.Message);
                        return false;
                    }

                    await ToastService.Success($"传感器{Sensor.Name}", "数据更新成功");
                    return true;
                }
            };
            await DialogService.ShowEditDialog(option);
        }
    }
}
